package com.yunduansing.demo.web.system;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.yunduansing.demo.exception.FileEmptyException;
import com.yunduansing.demo.exception.MyException;
import com.yunduansing.demo.exception.RecordExistsException;
import com.yunduansing.demo.model.common.PageRequestModel;
import com.yunduansing.demo.model.common.PageResultModel;
import com.yunduansing.demo.model.common.PassportModel;
import com.yunduansing.demo.model.common.ResponseModel;
import com.yunduansing.demo.model.user.*;
import com.yunduansing.demo.service.UserService;
import com.yunduansing.demo.util.ExcelUtils;
import com.yunduansing.demo.web.BaseController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;

/**
 * 系统用户控制器
 */
@Api(tags = "系统用户")
@RestController
public class UserController extends BaseController {
    @Autowired
    private UserService service;
    @Value("${file.upload}")
    private String baseUploadPath;

    /**
     * 分页
     * 
     * @param model
     */
    @GetMapping("/user/page")
    @ApiOperation(value = "分页")
    public ResponseModel<PageResultModel<UserPageModel>> getPage(UserPageRequestModel model) {
        return ok(service.getPage(model));
    }

    /**
     * 新增用户
     * 
     * @param model 新增用户模型
     * @return ResponseModel
     * @throws RecordExistsException
     */
    @PostMapping("/user/create")
    public ResponseModel create(@RequestBody UserAddModel model) throws RecordExistsException {
        return convertToResponseModel(service.create(model), "创建失败。");
    }

    /**
     * 修改用户
     * 
     * @param model 修改用户模型
     * @return ResponseModel
     * @throws RecordExistsException
     */
    @PostMapping("/user/update")
    public ResponseModel update(@RequestBody UserAddModel model) throws RecordExistsException {
        return convertToResponseModel(service.update(model), "修改失败。");
    }

    /**
     * 设置用户状态
     * 
     * @param ids
     * @param status 0-启用、1-禁用、2-锁定、3-删除
     * @return
     */
    @PostMapping("/user/set/status")
    @ApiOperation("设置用户状态")
    @ApiParam("ids-用户id集合")
    public Object setUserStatus(List<Integer> ids, int status) {
        return null;
    }

    @PostMapping("/user/upload")
    @ApiOperation("上传")
    @ApiParam(value = "文件，key为file", example = "formData.append('file');")
    public ResponseModel<String> upload(@RequestParam("file") MultipartFile file) throws FileEmptyException {
        if (file.isEmpty())
            throw new FileEmptyException("上传文件不能空！");
        String fileName = file.getOriginalFilename();// 得到文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 得到后缀名
        String filepath = baseUploadPath + "/user/images/";// 指定图片上传到哪个文件夹的路径
        File dir = new File(filepath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        fileName = UUID.randomUUID() + suffixName;// 重新命名图片，变成随机的名字
        File dest = new File(filepath + fileName);// 在上传的文件夹处创建文件
        try {
            file.transferTo(dest);// 把上传的图片写入磁盘中
            return ok("/file/user/images/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return convertToResponseModel(false, "上传失败。");
        }
    }

    @GetMapping("/user/detail")
    @ApiOperation("根据user id获取详情")
    public ResponseModel<UserPageModel> getDetailById(int id) {
        var result = service.getDetailById(id);
        return ok(result);
    }

    @GetMapping("/user/current")
    @ApiOperation("获取当前用户详情")
    public ResponseModel<UserPageModel> getCurrentUser() {
        var passport = this.getPassport();
        var result = service.getDetailById(passport.getUserId());
        return ok(result);
    }

    @PostMapping("/user/import")
    @ApiOperation("导入")
    public ResponseModel<Boolean> importData(@RequestParam("file") MultipartFile file) throws FileEmptyException {
        if (file.isEmpty())
            throw new FileEmptyException("上传文件不能空！");
        var data = ExcelUtils.readExcel("", UserImportModel.class, file);
        var result=service.importData(data);
        return ok(true);
    }

    @PostMapping("/user/reset/password")
    @ApiOperation("重置密码")
    public ResponseModel<Boolean> resetPassword(@RequestBody ResetPasswordModel model)
            throws RecordExistsException, MyException {
        var result=service.resetPassword(model.getUsername(), model.getOldPassword(), model.getNewPassword());
        return ok(result);
    }
}